#include <stdio.h>
#include "include/staff_db.h" 
#include "include/server.h"
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>





void *handler(void *sockfd)
{   
	int flag = 0;
    
    int *connfd = (int *)sockfd;
	MSG_C from_client_msg={};
	MSG_S to_client_msg = {};
	bzero(&from_client_msg, sizeof(MSG_C) );
	bzero(&to_client_msg, sizeof(MSG_S));
	while(1)
	{
		memset(&from_client_msg, 0, sizeof(from_client_msg));
		recv(*connfd,&from_client_msg, sizeof(MSG_C),0);
		if(flag == 0)
		switch(from_client_msg.type)
		{
			case 'l':
				flag=1;
				user_login_module(*connfd, &from_client_msg,&to_client_msg);
				printf("from: %s to  :%s\n", from_client_msg.text.name,to_client_msg.text.name);
				to_client_msg.text = from_client_msg.text;
				break;
			case 's':
				flag=1;
				user_search_info_module(from_client_msg.text.name, *connfd);
				break;
			case 'c':
				flag=1;
				orderuser_change_passwd_module(to_client_msg.text.name, from_client_msg.text.password, *connfd,to_client_msg);

				break;
			case 'a':
				flag=1;
				admin_add_userinfo_module(from_client_msg.text, *connfd,to_client_msg);
				break;
			case 'C':
				flag=1;
				admin_change_userinfo_module(*connfd,from_client_msg, to_client_msg);
				break;
			case 'd':
				flag=1;
				admin_del_userinfo_module(from_client_msg.text.name, *connfd, to_client_msg);
				break;
			case 'q':
				close(*connfd);
				printf("client1 exit\n");
				pthread_exit(NULL);
				break;
			default:
				strcpy(to_client_msg.error, "error order");
				send(*connfd, &to_client_msg, sizeof(MSG_S),0);
				break;
		}
		flag=0;
	}
}

int main(void)
{
	int connfd;
	int listenfd;
    Init_db("/staff.db"); //初始化数据库
    exec_sql(init_stafftable); //初始化表*/
	show_table("staff_table");

	listenfd = server_init();
	while(1)
	{	
		if((connfd = accept(listenfd,NULL,NULL))<0){
			perror("fail to accept");
			exit(1);
		}	
		pthread_t child_pthread;
		if(pthread_create(&child_pthread,NULL,handler,&connfd)<0)
		{
			perror("thread_create fail");
			exit(1);
		}
	}
	
	close(listenfd);
    return 0;
}
